//index.js
//获取应用实例
const app = getApp()
var bmap = require('../../utils/bmap-wx.min.js');
const util = require('../../utils/util.js');
Page({
  data: {
    imageUrl:"",
    // 此页面 页面内容距最顶部的距离
    height: app.globalData.height * 2 + 20,
    currentIndex: 0,
    swiper_images: [],
    allCategoryMessage: [],
    weatherData: null,
    floorstatus: "none",
    category_first: [],
    category_second: [],
    notice: [],
    lost_new: {},
    takeout: [],
    ad_bottom: ["../../images/other/1.png"],
    user_message: [],
    activeIndex: 1,
    isLastPage: false, //是否最后一页
    isUpdate: -1,
    isLoading: false //页面是否渲染完毕
  },
  onReady() {
    let that = this
    setTimeout(function() {
      that.setData({
        isLoading: true
      })
    }, 1000)

  },

  /**
   * 联系我
   */
  me_call() {
    wx.showModal({
      title: '提示',
      content: '如有需要请联系我',
      confirmText: "联系我",
      success: function(e) {
        if (e.confirm) {
          wx.makePhoneCall({
            phoneNumber: '18515063697',
          })
        }
      }
    })
  },
  //查看失物招领详情
  lookLostMessage(e) {
    wx.showModal({
      title: '失物招领',
      content: e.target.id,
      showCancel: false,
      confirmText: '已查阅'
    })
  },
  //商家查看
  to_shop(e) {
    wx.navigateTo({
      url: "/pages/shop_detail/shop_detail?shopId=" + e.target.id
    })
  },
  //查看最新的失物招领
  new_lost_look(e) {
    wx.navigateTo({
      url: "/pages/message_detail/message_detail?messageId=" + e.currentTarget.id
    })
  },
  //点击查看图片
  look_image(e) {
    wx.previewImage({
      urls: [e.target.id],
    });
  },
  //查看公告
  checkNotice(e) {
    wx.showModal({
      title: '公告',
      content: e.target.id,
      showCancel: false,
      confirmText: '已查阅'
    })
  },
  //授权天气
  getWeatherData() {
    let that = this;
    wx.openSetting({
      success: function(res) {
        if (res.authSetting && res.authSetting["scope.userLocation"]) {
          //允许授权,则自动获取定位，并关闭二确弹窗，否则返回首页不处理
          wx.showToast({
            title: '您已授权获取位置信息',
            icon: 'none'
          })
          that.getWeather();
        } else {
          wx.showToast({
            title: '需要授权才可以查看天气噢~',
            icon: 'none'
          })
        }
      }
    })
  },
  onPageScroll: function(e) { //判断滚轮位置
    if (e.scrollTop > 200) {
      this.setData({
        floorstatus: "block"
      });
    } else {
      this.setData({
        floorstatus: "none"
      });
    }
  },
  goTop: function(e) { // 一键回到顶部
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },
  //跳转到搜索页
  search: function() {
    wx.navigateTo({
      url: '/pages/search/search',
    })
  },
  //跳转到详情页
  to_message_detail: function(e) {
    wx.navigateTo({
      url: '/pages/message_detail/message_detail?messageId=' + e.currentTarget.id,
    })
  },

  /* getWeather() {
    var that = this;
    // 新建百度地图对象 
    var BMap = new bmap.BMapWX({
      ak: 'hTTpW43R5aKNRgoY5fcOiGFpdwuqI7TB'
    });
    var fail = function(data) {

    };
    var success = function(data) {
      var weatherData = data.currentWeather[0];
      weatherData = '城市：' + weatherData.currentCity + '\n' + 'PM2.5：' + weatherData.pm25 + '\n' +'日期：' + weatherData.date + '\n' + '温度：' + weatherData.temperature + '\n' +'天气：' + weatherData.weatherDesc + '\n' +'风力：' + weatherData.wind + '\n'; 
      that.setData({
        weatherData: weatherData
      });

    }
    // 发起weather请求 
    BMap.weather({
      fail: fail,
      success: success
    });
  } */
  getWeather() {
    var that = this;
    wx.getLocation({//用小程序官方api获取位置信息
      type: 'wgs84', // 获取位置信息必传参数
      success: (res) => { //成功之后的回调，开始请求天气api
        wx.request({
          //请求天气数据，通过经纬度
          url: 'https://devapi.qweather.com/v7/weather/now',
          data: {
            key: 'a33f4d0a70674452bb6b9173deff61d8', //和风天气api使用的key，需要先获取
            location: `${res.longitude},${res.latitude}` //经纬度，模板字符串拼接
          },
          header: {
            'content-type': 'application/json'
          },
          //箭头函数为了修改this指向
          success: (res) => {
            var weatherData = res.data.now;
            var obsTime = res.data.now.obsTime.slice(0,10)+" "+res.data.now.obsTime.slice(11,16)
            weatherData.obsTime = obsTime
            that.setData({
              weatherData: weatherData
            });
            // that.setData({
            //   temp: res.data.now.temp, //气温
            //   weather: res.data.now.text, //天气状况
            //   weatherIcon: res.data.now.icon //图标
            // })
            //return res.data.now.temp
          },
        })
      }
    })
  },

  onLoad: function(options) {
    let that = this
    this.getWeather();
    /**
     * 获取商店
     */
    wx.getStorage({
      key: 'shopMessage',
      success: function (res) {
          that.setData({
            takeout: res.data,
            imageUrl:app.globalData.imageUrl,
          })
          app.globalData.shopMessage = res.data
        },
      fail: function () {
        app.call({
          path: '/news/shop',
          method: "get",    
        }).then(res=>{
          that.setData({
              takeout: res.data.data,
              imageUrl:app.globalData.imageUrl,
            })
              wx.setStorage({
                key: 'shopMessage',
                data: res.data.data,
              })
              app.globalData.shopMessage = res.data.data
          })
      }
    }),
    /**
     * 获取轮播图
     */
    app.call({
      path: '/news/swiper',
      method: 'get',
    }).then(res=>{
      that.setData({
        swiper_images: res.data.data
      })
    }),
    
    /**
     * 分类信息
     */
    wx.getStorage({
      key: 'categoryMessage',
      success: function (res) {
        var get_first = res.data.slice(0, 10);
          var tem = [{}, {}, {}, {}, {}]
          var get_second = res.data.slice(10, 13).concat(tem)
          that.setData({
            category_first: get_first,
            category_second: get_second,
          })
        that.setData({
          allCategoryMessage: res.data
        })
        app.globalData.allCategoryMessage = res.data
      },
      fail: function () {
        app.call({
          path: '/news/categor',
          method: "get",    
        }).then(res=>{
          var get_first = res.data.data.slice(0, 10);
          var tem = [{}, {}, {}, {}, {}]
          var get_second = res.data.data.slice(10, 13).concat(tem)
          that.setData({
            category_first: get_first,
            category_second: get_second,
          })
          that.setData({
            allCategoryMessage: res.data.data
          })
          app.globalData.allCategoryMessage = res.data.data
          wx.setStorage({
            key: 'categoryMessage',
            data: res.data.data,
          })
          })
      },
    })
    /**
     * 获取公告
     */
    app.call({
      path: '/news/notice',
      method: "get",
    }).then(res=>{
      that.setData({notice: res.data.data})
    })
    /**
     * 获取最新第一页消息
     */
    app.call({
      path: '/news/getAllMessageDetail/1',
      method: "get",
    }).then(res=>{
      that.setData({
        user_message: res.data.data
      })
    })

    /**
     * 获取最新失物招领
     */
    app.call({
      path: '/news/lost',
      method: "get",
    }).then(res=>{
      if(res.data.code == 200){
        var lost = res.data.data[0]
        lost.messageCreatTime = util.formatDate(new Date(lost.messageCreatTime))
        that.setData({lost_new: lost})} 
    })
    
    
  },
  handleImgChange: function(e) {
    this.setData({
      currentIndex: e.detail.current
    })
  },
  /**
   * 下拉
   */
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    // 最后一页了，取消下拉功能
    if (this.data.isLastPage) {
      return
    }
    this.loadMessage(++this.data.activeIndex)
  },

  loadMessage(index) {
    wx.showLoading({
      title: '加载中~',
    })
    var that = this;
    console.log('loadMessage：'+index)
    const allMessageDetail = app.call({
      path: '/news/getAllMessageDetail/' + index,
      method: "get",})
    allMessageDetail.then(res=>{
      if(res.data.code == 200){
        that.setData({
          user_message: that.data.user_message.concat(res.data.data)
        })
        if (res.data.isLastPage) {
          that.setData({
            isLastPage: true
          })
          return;
        }
      }
    })
    allMessageDetail.finally(()=>{
      wx.hideLoading();
    })
  },
  onShow() {
    let that = this
    var app = getApp()
    app.call({
      path: '/news/getLastNewMessage/' + app.globalData.userId,
      method: 'get',}).then(res=>{
        if (res.statusCode != 200 || Object.keys(res.data.data).length<=0) {
          return
        }
        var net_res = res;
        wx.getStorage({
          key: 'lastNewMessage',
          success: function(res) {
            console.log('lastNewMessage：'+res.data)
            if (res.data != net_res.data.data.newMessageId) {
                var audioManager = wx.getBackgroundAudioManager();
                audioManager.src='http://downsc.chinaz.net/Files/DownLoad/sound1/201609/7824.wav';
                audioManager.play()
              wx.showModal({
                title: '新消息',
                content: '内容：' + net_res.data.newMessageDetail,
                confirmText: "去查看",
                cancelText: "稍后去看",
                success: function(e) {
                  if (e.confirm) {
                    wx.navigateTo({
                      url: '/pages/me_xiaoxi/me_xiaoxi',
                    })
                  }
                }
              })
            }
          },
        })
        wx.setStorage({
          key: 'lastNewMessage',
          data: net_res.data.data.newMessageId,
        })
      })
    /**
     * 判断是否更新
     */
    if (app.globalData.isUpdate == 1) {
      this.onLoad(),
        this.setData({
          activeIndex: 1,
          isLastPage: false, //是否最后一页
        })
      app.globalData.isUpdate = -1
    }

  }

})